package cn.wlinker.video.monitor.utils;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.StaticLog;
import cn.wlinker.video.monitor.config.StaticFileConfig;
import cn.wlinker.video.monitor.enums.FileTypeEnum;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.io.File;
import java.net.URLDecoder;

/**
 * 文件路径工具类
 *
 * @author gxsjx
 * @version 1.0
 * @date 2022/11/22
 */
@Slf4j
public class FilePathUtils {

    public static String getRandomNameWithPath(FileTypeEnum fileTypeEnum) {
        String uploadDir = FilePathUtils.getUploadDir(fileTypeEnum);
        cn.hutool.core.lang.Assert.notBlank(uploadDir, "获取上传目录失败");
        return StrUtil.format("{}{}.{}", uploadDir, UUID.fastUUID(), fileTypeEnum.name());
    }

    @SneakyThrows
    public static String getUploadDir(FileTypeEnum fileTypeEnum) {
        String path = FileTypeEnum.getPath(fileTypeEnum.name());
        //上传目录地址
        String uploadDir = StaticFileConfig.getBaseFileDir() + path;
        Assert.notNull(uploadDir, "上传目录未配置");
        uploadDir = URLDecoder.decode(uploadDir, "UTF-8");
        //如果目录不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            boolean mkdir = dir.mkdirs();
            if (Boolean.FALSE.equals(mkdir)) {
                StaticLog.warn("创建目录{}失败", uploadDir);
                return null;
            }
        }
        return uploadDir;
    }

    @SneakyThrows
    public static String getUrlPathByFileName(String filePath) {
        String fileName = FileNameUtil.getName(filePath);
        ServerUrlGenerator serverUrlGenerator = SpringUtil.getBean(ServerUrlGenerator.class);
        String extName = FileNameUtil.extName(fileName);
        String path = FileTypeEnum.getPath(extName);
        String baseUrl = serverUrlGenerator.generateBaseUrl();
        return StrUtil.format("{}/file/{}{}", baseUrl, path, fileName);
    }
}
